import { writable } from "svelte/store";
import type { Point } from "@/components/Point/type";
import type { BadgeType } from "@/components/Badge/type";
import { collegeUrl, getAlarmRecord, getDeviceCatelog, getDeviceRuntime, getDeviceStatus } from "../api";
import { run } from "svelte/internal";

export interface Track {
  id: number
  path: Point[]
}

function createTracks() {
  const { subscribe, set, update } = writable<Track[]>([])
  const currentCar = writable<number>()
  subscribe((tracks: Track[]) => {
    const len = tracks.length
    let i = 0
    let interval
    if (len > 0) {
      currentCar.set(tracks[i].id)
      interval = setInterval(() => {
        currentCar.set(tracks[i++ % len].id)
      }, 4000)
    }
    return function () {
      if (interval) {
        clearInterval(interval);
      }
    };
  })
  return {
    subscribe, set, update, currentCar,
    get: async () => {
      const response = await fetch('/mock/index/tracks.json')
      const data = await response.json()
      set(data)
    },
  }
}

export const tracks = createTracks()

export interface Monitor {
  id: string
  vinNo: string
  vinStatus: string
  voltage: string
  current: string
  speed: string
}

function createMonitor() {
  const { subscribe, set, update } = writable<Monitor>(null)

  return {
    subscribe, set, update,
    get: async (id) => {
      const response = await fetch('/mock/index/monitors.json')
      const data = await response.json()
      const monitor = data.find(monitor => monitor.id === id)
      set(monitor)
    },
  }
}

export const monitor = createMonitor()

tracks.currentCar.subscribe((cur: number) => {
  monitor.get(cur)
})


export interface College {
  name: string
  type: BadgeType
  value: string
}
export interface CollegeCollection {
  colleges: College[]
  index: number
}

function createCollege() {
  const { subscribe, set, update } = writable<CollegeCollection>({ colleges: [], index: 0 })
  return {
    subscribe, set, update,
    get: async () => {
      // const response = await fetch('/mock/index/status.json')
      const response = await fetch(collegeUrl)
      const { data = [] } = await response.json()
      const colleges = (data || []).map((item: any) => {
        return {
          name: item.dictLabel,
          type: item.dictLabel === "智慧工厂" ? 'factory' : 'college',
          value: item.dictValue,
        }
      })
      const interval = setInterval(() => {
        update(({ colleges, index }) => ({ colleges, index: (index + 1) % 4 }))
      }, 4000)
      set({ colleges, index: 0 })
    },
  }
}

export const collegeCollection = createCollege()


export interface Status {
  id: number,
  normal: number
  warning: number
  error: number
  offline: number
}

function createStatus() {
  const { subscribe, set, update } = writable<Status>({ error: 0, id: 0, normal: 0, offline: 0, warning: 0 })

  return {
    subscribe, set, update,
    get: async (id: string) => {
      // const response = await fetch('/mock/index/status.json')
      // const data = await response.json()
      const response = await fetch(getDeviceStatus)
      const { data = [] } = await response.json()
      const status = data.find(s => +s.id === +id)
      set(status)
    },
  }
}

export const status = createStatus()

function createCatalog() {
  const { subscribe, set, update } = writable<any>({})

  return {
    subscribe, set, update,
    get: async (id) => {
      // const response = await fetch('/mock/index/catalog.json')
      // const data = await response.json()
      const response = await fetch(getDeviceCatelog)
      const { data = [] } = await response.json()
      const status = data.find(s => +s.id === +id)
      set(status)
    },
  }
}

export const catalog = createCatalog()


collegeCollection.subscribe((item) => {
  const { colleges = [], index } = item
  const college = colleges[index]
  if (college) {
    status.get(college.value)
    catalog.get(college.value)
  }
})

export interface Realtime {
  name: string
  type: string
  status: string
  timer: string
}

function createRealtime() {
  const { subscribe, set, update } = writable<Realtime[]>([])

  return {
    subscribe, set, update,
    get: async () => {
      // const response = await fetch('/mock/index/realtime.json')
      // const realtime = await response.json()
      const response = await fetch(getAlarmRecord)
      const { data = [] } = await response.json()
      set(data)
    },
  }
}

export const realtime = createRealtime()

export interface Runtime {
  deviceName: string
  runTime: number
  locationId: number
  createTime: string
}

export interface RuntimeSeries {
  catalog: string[],
  series: {
    name: string,
    data: number[]
  }[]
}

function createDeviceRutime() {
  const { subscribe, set, update } = writable<RuntimeSeries>({ catalog: [], series: [] })
  return {
    subscribe, set, update,
    get: async (id?: number) => {
      let url = getDeviceRuntime
      if (id) {
        url = `${url}?locationId=${id}`
      }
      const response = await fetch(url)
      const { data = {} } = await response.json()
      const timeMap = {}
      const timeDeviceMap = {}
      const devices = Object.keys(data)
      devices.forEach(key => {
        const item = data[key] || []
        timeDeviceMap[key] = {}

        item.forEach(im => {
          timeMap[im.createTime] = null
          timeDeviceMap[key][im.createTime] = im
          im.runTime = +im.runTime
        })
      })
      const times = Object.keys(timeMap).sort()

      const series = devices.map((key) => {
        const deviceMap = timeDeviceMap[key] || {}
        const data = times.map(time => {
          const device = deviceMap[time] || {}
          return device.runTime || 0
        })
        return { name: key, data }
      })

      set({ catalog: times, series })
    },
  }
}

export const runTime = createDeviceRutime()

